package ihs;

import java.util.HashMap;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.MarkerUtilities;

public class MarkerFactory {

	public static void addMarkerToActiveWindow(int lineNumber, String text, int numberOfLines) {

		IFile file = (IFile) (PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor()
				.getEditorInput().getAdapter(IFile.class));

		String filename = file.getFullPath().toString();
		Marker temp = new Marker(text, lineNumber);
		List<Marker> currentMarkers = IHSPlugin.getDefault().addMarker(
				filename, temp, numberOfLines);

		removeMarkers(file);
		addMarkersToFile(file, currentMarkers);

	}

	private static void addMarkersToFile(IFile aFile, List<Marker> markers) {
		int offset;
		if(markers.size() < 3) {
			offset = 10 - markers.size() + 1;
		} else {
			offset = 10 / markers.size();
		}
		
		int x = 0;
		for (Marker marker : markers) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			MarkerUtilities.setLineNumber(map, marker.lineNumber);
			MarkerUtilities.setMessage(map, marker.text);

			try {
				MarkerUtilities.createMarker(aFile, map, IHSPlugin.MARKERS[x]);
			} catch (CoreException e) {
				throw new Error("Failed To Add Marker", e);
			}
			x += offset;
		}
	}

	private static void removeMarkers(IFile file) {
		try {
			for (String marker : IHSPlugin.MARKERS) {
				file.deleteMarkers(marker, true, IResource.DEPTH_INFINITE);
			}
		} catch (CoreException e) {
			throw new Error("Failed To Remove Markers");
		}
	}

}
